import json
import os
import time
import uuid
import random

from flask import Blueprint, request, jsonify
from RedisTool import r
from application.models.users.user import db, Course, Tcourse, Orders, OrdersDetail, Jie, CommentType, User, Comment
from tools.comm import get_ali_object

course_blue = Blueprint("course_blue", __name__)


# 获取课程详情
@course_blue.route("/getDetail", methods=["GET"])
def getDetail():
    # 获取id
    cid = request.args.get('cid')
    userid = request.args.get('userid')
    # 查询课程信息
    course = Course.query.filter(Course.id == cid).first()
    # 加载浏览记录，获取userid
    if userid:
        key = "collection" + str(userid) + 'pro' + str(cid)
        r.hash_add(key, 'id', course.id)
        r.hash_add(key, 'name', course.name)
        r.hash_add(key, "url", course.url)
    # 返回课程信息
    dict = {}
    dict['id'] = course.id
    dict['ctype'] = course.ctype
    dict['name'] = course.name
    dict["url"] = course.url
    # 获取课程下所有的章节
    jies = Jie.query.order_by(Jie.tcount.asc()).filter(Jie.courseid == cid).all()
    list = []
    for i in jies:
        list.append({'id': i.id, 'name': i.name, 'url': i.url, 'tcount': i.tcount})
    dict['jies'] = list
    return jsonify({"code": 200, 'course': dict})


# 获取最近浏览
@course_blue.route("/getViews", methods=["GET"])
def getViews():
    # 获取id
    userid = request.args.get("userid")
    findkey = "collection" + str(userid) + '*'
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict = {}
        for k, v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    return jsonify({"code": 200, "list": reslist})


# 加入购物车
@course_blue.route("/buy", methods=["GET"])
def buy():
    # 获取参数 userid courseid
    userid = request.args.get("userid")
    courseid = request.args.get("courseid")
    # 加减类型
    type1 = 1
    try:
        type1 = request.args.get("type")
        print('>>>>>>>>>>>>>>>>>>>>>>type1', type1)
    except:
        pass
    # 从hash中获取数据，如果存在数量+1 buy1course2
    key = "buy" + str(userid) + "course" + str(courseid)
    # 如果不存在存入redis hash
    flag = r.findkey_hash(key)
    # 存在
    if flag:
        # 数量+1
        ff = r.jiajian_hash(key, "number", 1, type1)
        if ff == False:
            return jsonify({"code": 300, "msg": "不能在减了"})
    else:
        r.jiajian_hash(key, "id", courseid, type1)
        r.jiajian_hash(key, "number", 1, type1)
        # 默认为选中
        r.hash_add(key, "flag", "True")
    return jsonify({"code": 200, "msg": "加入购物车成功"})


# 获取购物车
@course_blue.route("/mycart", methods=["GET"])
def mycart():
    # 获取参数userid
    userid = request.args.get("userid")
    # 从hash中获取商品id和数量
    key = "buy" + str(userid) + "*"
    goods = r.getvalues(key)
    glist = []
    tmoney = 0
    tcount = 0
    if goods:
        for i in goods:
            # 获取每一条商品的具体信息
            good = r.getall_hash(i)
            rescourse = {}
            for k, v in good.items():
                params = k.decode()
                values = v.decode()
                if params == "id":
                    tcourse = Tcourse.query.filter(Tcourse.id == values).first()
                    rescourse["id"] = tcourse.id
                    rescourse["name"] = tcourse.title
                    rescourse["url"] = tcourse.url
                    rescourse["price"] = tcourse.price
                if params == "number":
                    # 获取到数据库商品数量
                    rescourse["number"] = values
                if params == "flag":
                    if values == "True":
                        rescourse["flag"] = True
                    else:
                        rescourse["flag"] = False
            rescourse["total"] = int(rescourse["price"]) * int(rescourse["number"])
            # 计算总价格
            if rescourse["flag"] == True:
                tmoney = float(tmoney) + float(rescourse["total"])
                tcount = int(tcount) + int(rescourse["number"])
            glist.append(rescourse)
    # 价格，图片，名字      从mysql中获取，从redis商品缓存中读取
    # 数据重组返回
    return jsonify({"code": 200, "glist": glist, "tmoney": tmoney, "tcount": tcount})


# 获取训练营课程
@course_blue.route("/bootcamp", methods=["GET"])
def bootcamp():
    # 获取数据库存储的所有训练营课程
    trouse = Tcourse.query.all()
    # 序列化
    clist = [{"id": i.id,
              "name": i.title,
              "url": i.url,
              "price": i.price,
              "store": i.store,
              "intor": i.intro
              } for i in trouse]
    # 返回
    return jsonify({"code": 200, "clist": clist})


# 修改单个选中
@course_blue.route('/modifyStatus', methods=['GET'])
def modifyStatus():
    # 接收参数 userid  goodsid
    userid = request.args.get('userid')
    cid = request.args.get('cid')
    # 获取过来的判断状态
    key = "buy" + str(userid) + "course" + str(cid)
    flag = r.getone_hash(key, "flag")
    # 设置默认为选中
    cflag = "True"
    # 如果true改为false，如果false改为true
    if flag:
        flag = flag.decode()
        # 根据返回结果选中相反的
        if flag == "True":
            cflag = "False"

        r.hash_add(key, "flag", cflag)
    return jsonify({"code": 200})


#  全选
@course_blue.route("/modifyAllStatus")
def modifyAllStatus():
    userid = request.args.get('userid')
    status = request.args.get('status')
    flag = "false"
    if status == "true":
        flag = "True"
    # 把购物车全部修改为选中或者未选中
    keys = r.getvalues("buy" + str(userid) + "*")
    for i in keys:
        r.hash_add(i, 'flag', flag)
    return jsonify({"code": 200})


# 生成订单
@course_blue.route("/create_orders", methods=['POST'])
def create_orders():
    # 接收参数userid
    data = json.loads(request.data)
    userid = int(data['userid'])
    # 接口幂等性验证
    order_token = data['order_token']
    print("**********", order_token)
    value = r.str_get(order_token)
    print("=========", value)
    if not value:
        return jsonify({'code': 10010, "mes": "已经生成不能重复操作"})
    # 删除
    r.str_del(order_token)
    # 根据userid查询购物车
    key = "buy" + str(data['userid']) + "*"
    glist = r.getvalues(key)
    # 生成订单号
    order_no = str(random.randint(100, 999)) + str(data['userid'])
    totalmoney = 0
    try:
        if glist:
            # 写入订单表
            orders = Orders(order_no=order_no, userid=userid)
            db.session.add(orders)
            # 写入订单详情表
            for i in glist:
                flag = r.getone_hash(i, "flag")
                if flag:
                    flag = flag.decode()
                    if flag == 'True':
                        id = r.getone_hash(i, "id")
                        id = id.decode()
                        number = r.getone_hash(i, "number")
                        number = number.decode()
                        # 判断购物车中已选中的记录
                        tcourse = Tcourse.query.filter(Tcourse.id == id).first()
                        # 查询训练营课程表，判断库存
                        if int(tcourse.store) < int(number):
                            return jsonify({"code": 200, 'mes': "库存不够"})
                        # 写入订单详情表
                        tmoney = float(tcourse.price) * float(number)
                        detail = OrdersDetail(order_no=order_no, courseid=id, cname=tcourse.title, number=number, price=tcourse.price, tmoney=tmoney)
                        db.session.add(detail)
                        # 总价
                        totalmoney = totalmoney + tmoney
                        # 删除购物车已经选中的记录
                        # r.del_hash(i)
            orders.tmoney = totalmoney
            db.session.add(orders)
            db.session.commit()
            return jsonify({'code': 200, 'mes': "购买成功", 'orderno': order_no})
    except:
        return jsonify({'code': 10010, 'mes': "购买失败"})


# 生成uuid 验证订单token
@course_blue.route("/get_order_token")
def get_order_token():
    # 生成uuid
    token = uuid.uuid1().hex
    print("token>>>>", token)
    # 将token存入redis
    r.str_add(token, '1')
    # 返回结果
    return jsonify({'code': 200, 'token': token})


# 展示订单表信息  ORM
@course_blue.route("/orders")
def orders():
    order_no = request.args.get('order_no')
    orderdict = {}
    orders = Orders.query.filter(Orders.order_no == order_no).first()
    if orders:
        orderdict["order_no"] = orders.order_no
        orderdict["tmoney"] = orders.tmoney
        list = []
        for i in orders.details:
            list.append({"courseid":i.courseid,"cname":i.cname,"number":i.number,"price":i.price,"tmoney":i.tmoney})
        orderdict['orderdict'] = list
    return jsonify({'code':200,"orders":orderdict})


# # # 展示订单表信息 原生SQL
# @course_blue.route("/orders")
# def orders():
#     order_no = request.args.get('order_no')
#     sql = "select o.order_no,o.tmoney,od.order_no,od.courseid,od.cname,od.number,od.price,od.tmoney from orders as o inner join orders_detail as od on o.order_no=%d" % int(order_no)
#     res = db.session.execute(sql)
#     data = res.fetchall()
#     list = []
#     idlist = []
#     # 拿到父类
#     for i in data:
#         if i[0] not in idlist:
#             dict = {"id": i[0], "tmoney": i[1], "orderdict": []}
#             list.append(dict)
#             idlist.append(i[0])
#     # 遍历list
#     for (index, j) in enumerate(list):
#         for i in data:
#             if i[2] == j["id"]:
#                 list[index]["orderdict"].append({"order_no": i[2], "gid": i[3], "cname": i[4], "number": i[5], "price": i[6], "tmoney": i[7]})
#     return jsonify({'code': 200,"orders":list})


# 支付宝支付
@course_blue.route("/buytcourse", methods=['POST'])
def buytcourse():
    # 订单号
    order_no = request.args.get('order_no')
    orders = Orders.query.filter(Orders.order_no == order_no).first()
    # 支付，返回支付url
    pay = get_ali_object()
    # 生成支付的url
    # 订单号重构充值1 支付订单2
    order_no = str(order_no) + ":" + str(1)
    query_params = pay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(orders.tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code': 200, 'url': pay_url})


# 添加课程章节节课
@course_blue.route("/addjie", methods=["POST"])
def addjie():
    # 获取参数
    data = json.loads(request.data)
    if not data:
        return jsonify({"code": 10010, "mes": "参数错误"})
    # 添加课程章节
    name = data['name']
    url = data['url']
    tcount = data['tcount']
    courseid = data['courseid']
    try:
        jie = Jie(name=name, url=url, tcount=tcount, courseid=courseid)
        db.session.add(jie)
        db.session.commit()
    except Exception as e:
        print(e)
        return jsonify({"code": 10010, "mes": "章节添加失败"})
    return jsonify({"code": 200, "mes": "章节添加成功"})


# 上传图片
@course_blue.route("/upload",methods=['POST'])
def upload():
    # 获取文件
    file = request.files.get("file")
    path = os.path.join("static/upload/media/"+file.filename)

    # 保存文件
    file.save(path)
    # 删除
    # 通过id获取导数据url
    # 删除数据库
    # url = "static/upload/腾讯会议图片_20220408184958.png"
    # os.remove(url)
    return jsonify({'code':200,"url":path})


# 获取评价信息
@course_blue.route("/comments",methods=['POST','GET'])
def comments():
    if request.method == "GET":
        # 获取分类
        types = CommentType.query.all()
        tlist = [{
            "id": i.id,
            "name": i.name
        } for i in types]
        # 获取默认分类吓得评论
        # 查询此分类下面的评论及回复
        sql = "select u.url,u.nikename,u.level,c.title,c.tcount,c.tviews,c.id,c.create_time from comment as c inner join user as u on c.userid=u.id where c.pid=0"
        res = db.session.execute(sql)
        comments = res.fetchall()
        commentslist = []
        for i in comments:
            ctime = i['create_time']
            hour = int((int(time.time()) - int(time.mktime(ctime.timetuple()))) / 3600)
            commentslist.append({'url':i[0],'nikename':i[1],'level':i[2],'title':i[3],'tcount':i[4],'tviews':i[5],'id':i[6],'times':hour})
        qqq = "select u.nikename,u.level,c.create_time from user as u inner join comment as c on u.id = c.userid where c.is_last=1"
        www = db.session.execute(qqq)
        ucomment = www.fetchall()
        ucommentslist = []
        for i in ucomment:
            ctime = i['create_time']
            hour = int((int(time.time()) - int(time.mktime(ctime.timetuple())))/3600)
            ucommentslist.append({'nikename':i[0],'level':i[1],'times':hour})
        return jsonify({'code':200,"tlist":tlist,"commentslist":commentslist,"ucommentslist":ucommentslist})
    else:
        # 获取参数 userid comment 评价id
        userid = 5
        comment = "2342342342342"
        # 被评价的id
        cid = 1
        # 分类id
        typepid = 1
        comment = Comment(title=comment,is_last=1,userid=userid,typepid=typepid,pid=cid,send_id=cid)
        db.session.add(comment)
        db.session.commit()
        return jsonify({"code":200})


@course_blue.route("/getcomments")
def getcomments():
    id = request.args.get("id")
    sql = "select u.url,u.nikename,u.level,c.title,c.tcount,c.tviews,c.create_time from comment as c inner join user as u on c.userid = u.id where c.id = %s" % id
    res = db.session.execute(sql)
    comments = res.fetchall()
    print("===========",comments)
    cslist = []
    for i in comments:
        ctime = i[6]
        hour = int((int(time.time()) - int(time.mktime(ctime.timetuple())))/3600)
        cslist.append({"url":i[0],"nikename":i[1],"level":i[2],'title':i[3],'tcount':i[4],'tviews':i[5],"times":hour})
        print("===========", cslist)

    qqq = "select u.url,u.nikename,u.level,c.create_time from comment as c inner join user as u on c.userid = u.id where c.pid = %s" % id
    www = db.session.execute(qqq)
    ucomment = www.fetchall()
    ulist = []
    for i in ucomment:
        ctime = i['create_time']
        hour = int((int(time.time()) - int(time.mktime(ctime.timetuple()))) / 3600)
        ulist.append({'url':i[0],'nikename': i[1], 'level': i[2], 'times': hour})
    return jsonify({'code':200,'commentslist':cslist,'ulist':ulist})


# 课程章节选择课程添加
@course_blue.route("/get_course", methods=['GET'])
def add_chapter():
    # 获取全部课程
    course = Course.query.all()
    # 课程章节列表
    list = []
    for i in course:
        dict = {"id": i.id, "name": i.name}
        list.append(dict)
    return jsonify({"code": 200, "list": list})

